const Koa = require('koa');
const cors = require('@koa/cors');
const routes = require('./routes');
const sequelize = require('./config/database');
const config = require('./config/config.js')
const bodyParser = require('koa-bodyparser');
const koaStatic  = require('koa-static');
const app = new Koa();
const path=require("path")
let fs=require("fs")
const send = require('koa-send');
// Middlewares
app.use(cors());
app.use(bodyParser()) //使用 bodyParser 中间件来解析 POST 请求体

app.use(routes.routes()).use(routes.allowedMethods());
// 下载路由
app.use(koaStatic(path.join(process.cwd(), 'public')));
app.use(async (ctx, next) => {
    const filePath = path.join(process.cwd(), 'public/uploads/file', ctx.path);
    if (fs.existsSync(filePath)) {
        ctx.set('Content-Disposition', 'attachment; filename=' + path.basename(filePath));
        ctx.body = fs.createReadStream(filePath);
    } else {
        await next();
    }
});
// 启动数据库连接并启动服务器
sequelize.authenticate()
    .then(() => {
        console.log('Database connected');
        app.listen(3000, () => {
            console.log('Server is running on http://localhost:' + config.server.httpPort);
        });
    })
    .catch(err => {
        console.error('Database connection failed:', err);
    });
